import {ajaxGet} from '@/util'
export default({
  state: {
    dealerList: [],
    dealeredList: [],
    total: 0
  },
  mutations: {
    allDealerList(state, data) {
      state['dealerList'] = data.map(item => {
        return {
          id: item.distributorId,
          value: item.distributorName
        }
      })
    },
    fillDealeredList(state, data) {
      state['dealeredList'] = data || []
    },
    onSetDealer(state) {
      // state['dealeredList'] = [] // 新增时，要把dealeredList置为空数组(会有前一次保存时的dealeredList的数据在，所以要先置空[])
      // let allIds = state['dealerList'].map(item => item.id)
      // arr.forEach(item => {
      //   let indexOf = allIds.indexOf(item)
      //   if (indexOf >= 0) {
      //     state['dealeredList'].push(state['dealerList'][indexOf])
      //     state['dealerList'].splice(indexOf, 1)
      //   }
      // })
      state['dealeredList'].forEach(item => {
        let indexOf = state['dealerList'].findIndex(m => m.id === item.id)
        if (indexOf >= 0) {
          state['dealerList'].splice(indexOf, 1)
        }
      })
    },
    deleteDealer(state, object) {
      state['dealeredList'].splice(object.index, 1)
      state['dealerList'].unshift(object.item)
    },
    joinDealer(state, object) {
      state['dealerList'].splice(object.index, 1)
      state['dealeredList'].push(object.item)
    },
    onChangeAllDealer(state) {
      if (!state['dealerList'].length) return
      // state['dealeredList'].push(...JSON.parse(JSON.stringify(state['dealerList'])))
      state['dealeredList'].push(...state['dealerList'])
      state['dealerList'] = []
    },
    onCancelAllDealer(state) {
      if (!state['dealeredList'].length) return
      state['dealerList'].push(...JSON.parse(JSON.stringify(state['dealeredList'])))
      state['dealeredList'] = []
    }
  },
  actions: {
    getOperDealerList({state, commit}, param) {
      return new Promise((resolve, reject) => {
        ajaxGet("/freight/setting/distributorPage", param).then(data => {
          commit('allDealerList', data.records)
          state['total'] = Number(data.total)
          resolve(data)
        })
      })
    },
    setEditDealerData({state, commit}) {
      commit('onSetDealer')
    }
  },
  getters: {
    caggiageDealerList: (state) => state.dealerList,
    caggiageDealeredList: (state) => state.dealeredList,
    caggiageTotal: (state) => state.total
  }
})